var $menuList = $('#menuList');
var $organizationList = $('#organizationList');
var $buttonList = $("#buttonList");
var $otherList = $("#otherList");

//改颜色
function changeColor(roleId){
	//背景颜色白色 字体黑色
	$('.context-menu-one').css("background-color","#fff");
	$('.context-menu-one').css("color","#666");
	$('.final-menu').css("background-color","#fff");
	// 选中 背景颜色橙色 字体白色
	$('#'+roleId).css("background-color","#fe7f27");
	$('#'+roleId).css("color","#fff");
	$('#'+'li'+roleId).css("background-color","#fe7f27");
}

$(function() {	
	$('#side-menu').contextMenu({
        selector: 'li', 
        callback: function(key, options) {
        	// 获取当前roleId
        	var id = $(this).children('span').attr('id');
            if(key == "copy"){
            	// 复制
				$("#srcOrmemberId").val(id);
				
            }else if(key == "paste"){
            	//粘贴覆盖权限菜单
            	var destId = id;
				var srcId = $("#srcOrmemberId").val();
				if (srcId != '0' && srcId.length > 0) {
					$('#roleId').val(id);
					changeColor(destId);
					copyOrmemberMenuToNext(srcId,destId,false);
				} else {
					toastr.warning('', '请先选择要复制的角色');
				}
            }else if(key == "mpaste"){
            	//粘贴合并权限菜单
            	var destId = id;
				var srcId = $("#srcOrmemberId").val();
				if (srcId != '0'&& srcId.length > 0) {
					$('#roleId').val(id);
					changeColor(destId);
					copyOrmemberMenuToNext(srcId,destId,true);
				} else {
					toastr.warning('', '请先选择要复制的源角色');
				}
            }else if(key == "delete"){
            	$('#roleId').val(id);
            	changeColor(destId);
            	//清空权限菜单
            	clearEmpOrOrmemberMenu(id);
            }
        },
        items: {
            "copy": {name: "复制当前菜单", icon: "copy"},
            "paste": {name: "粘贴覆盖权限菜单", icon: "cut"},
            "mpaste": {name: "粘贴合并权限菜单", icon: "paste"},
            "delete": {name: "清空权限菜单", icon: "delete"}
        }
        
        
    });

    $('li').on('click', function(e){
    	var id = '';
    	// 如果是点击角色列表，获取该角色roleId,否则获取记录的roleId
    	if($(this).attr('class') == 'final-menu'){
            id = $(this).children('span').attr('id');
    	}else{
    		id = $('#roleId').val();
    	}
        console.log('clicked', $(this).text());
        // 如果ID长度大于0，点击的是角色列表
        //赋值
    	$('#roleId').val(id);
        // 改变颜色
        changeColor(id);
        if($(this).text() != '复制当前菜单'){
            //刷新菜单
        	ajaxRefreshMenuList();
        	$('#belongSystemTemp').show();
        }
    });
    $(".defaultHidding").mouseover(function () {
    	$(".defaultHidding").css("overflow", "visible");
    });
    $(".defaultHidding").mouseout(function () {
    	$(".defaultHidding").css("overflow", "hidden");
    });
    changeBelogSystem();
});

var flag = true;
// 更新权限菜单
function ajaxRefreshMenuList() {
	var roleId = $('#roleId').val();
	$.ajax({
		type : 'POST',
		dataType : "json",
		async : false,
		cache:false,
		url : ctx + 'sys/oper/roleAuth/ajaxMenuList.do',
		data : {
			'roleId' : roleId,
			'belongSystem' : $('#belongSystem').val()
		},
		success : function(data) {
			// 按钮菜单清空
			$("#buttonList").html('');
			// 其他权限清空
			$("#otherList").html("");
			// 清空菜单
			$menuList.remove();
			$('<div id="menuList"></div>').appendTo($("#menuList-ibox"));
			$menuList = $("#menuList");
			$menuList.jstree({
				'core' : {
					data : data,
					"themes" : {
						"name" : "default",
						"dots" : false,
						"icons" : false
					}
				},
				'plugins' : [ 'checkbox', 'wholerow' ]

			}).on("changed.jstree", function(e, data) {
				//console.info(data.selected.length)
				var doms = $menuList.jstree("get_selected", true);
				var menuIds = '';
				$.each(doms, function(i, dom) {
					if ($menuList.jstree("is_leaf", dom)) {
						menuIds += $(dom).attr('id') + ',';
					}
				});
				refreshButtonMenu(roleId, menuIds);
				refreshOtherButtonMenu(roleId, menuIds);
			});
		},
		error : function(e) {
			console.log(e);
		}
	});
}

function refreshButtonMenu(roleId, menuIds) {
	$.ajax({
		type : 'POST',
		dataType : "json",
		async : false,
		cache:false,
		url : ctx + 'sys/oper/roleAuth/ajaxDisplayButtonMenu.do',
		data : {
			'menuIds' : menuIds,
			'roleId' : roleId,
			'mType' : '1',
			'belongSystem' : $('#belongSystem').val()
		},
		success : function(data) {
			$buttonList.remove();
			$('<div id="buttonList"></div>').appendTo($("#buttonList-ibox"));
			$buttonList = $("#buttonList");
			if (data && data.length > 0) {
				// 清空按钮菜单
				$buttonList.jstree({
					'core' : {
						data : data,
						"themes" : {
							"name" : "default",
							"dots" : false,
							"icons" : false
						}
					},
					'plugins' : [ 'checkbox', 'wholerow' ]

				});
			}
		},
		error : function(e) {
			toastr.warning('', '保存出错，请检查重新操作');
		}
	});
}

function refreshOtherButtonMenu(roleId, menuIds) {
	$.ajax({
		type : 'POST',
		dataType : "json",
		async : false,
		cache:false,
		url : ctx + 'sys/oper/roleAuth/ajaxDisplayButtonMenu.do',
		data : {
			'menuIds' : menuIds,
			'roleId' : roleId,
			'mType' : '2',
			'belongSystem' : $('#belongSystem').val()
		},
		success : function(data) {
			$otherList.remove();
			$('<div id="otherList"></div>').appendTo($("#otherList-ibox"));
			$otherList = $("#otherList");
			if (data && data.length > 0) {
				$otherList.jstree({
					'core' : {
						data : data,
						"themes" : {
							"name" : "default",
							"dots" : false,
							"icons" : false
						}
					},
					'plugins' : [ 'checkbox', 'wholerow' ]

				});
			}
		},
		error : function(e) {
			toastr.warning('', '保存出错，请检查重新操作');
		}
	});
}

// 清空权限菜单
function clearEmpOrOrmemberMenu(roleId) {
	$.ajax({
		type : 'POST',
		dataType : "json",
		cache:false,
		url : ctx + 'sys/oper/roleAuth/clearMenu.do',
		data : {
			'roleId' : roleId,
			'belongSystem' : $('#belongSystem').val()
		},
		success : function(data) {
			if ('success' == data) {
				ajaxRefreshMenuList();
				toastr.success('', '操作成功');
			}
		},
		error : function(e) {
			toastr.warning('', '保存出错，请检查重新操作');
		}
	});
}

// 复制一个角色权限菜单给另一个角色
function copyOrmemberMenuToNext(srcId, destId,merge) {
	$.ajax({
		type : 'POST',
		dataType : "json",
		cache:false,
		url : ctx + 'sys/oper/roleAuth/copyOrmemberMenuToNext.do',
		data : {
			'srcId' : srcId,
			'destId' : destId,
			'merge'  : merge,
			'belongSystem' : $('#belongSystem').val()
		},
		success : function(data) {
			console.log(data);
			if ('success' == data) {
				ajaxRefreshMenuList();
				toastr.success('', '操作成功');
			}
		},
		error : function(e) {
			toastr.warning('', '保存出错，请检查重新操作');
		}
	});
}

// 保存按钮进行保存选中的菜单
function ajaxSaveMenuAuth() {
	//禁用保存按钮
	$('#buttonSave').attr('disabled',true);
	var event = event || window.event;
	var target = event.target || event.srcElement;
	var targetx = $(target);
	targetx.button('loading');

	var roleId = $("#roleId").val();
	
	var selected = $menuList.jstree("get_selected", true);
	var menuIds = '';
	// 保存左边菜单ID
	$.each(selected, function(i, dom) {
		if ($menuList.jstree('is_leaf', dom)) {
			var id = $(dom).attr('id');
			if(id != menuList){
				menuIds += $(dom).attr('id') + ',';
			}
		}
	});
	// 保存右边按钮菜单ID
	var btnSelected = $buttonList.jstree("get_selected", true);
	$.each(btnSelected, function(i, dom) {
		if ($buttonList.jstree('is_leaf', dom)) {
			var id = $(dom).attr('id');
			if(id != 'buttonList'){
				menuIds += $(dom).attr('id') + ',';
			}
		}
	});
	// 保存其他权限ID
	var otherBtnSelected = $otherList.jstree("get_selected", true);
	$.each(otherBtnSelected, function(i, dom) {
		if ($otherList.jstree('is_leaf', dom)) {
			var id = $(dom).attr('id');
			if(id != 'otherList'){
				menuIds += $(dom).attr('id') + ',';
			}
		}
	});
	if (roleId.length == 0) {
		toastr.warning('', '请选择角色或人员');
		$(targetx).button('reset');
		return;
	}
	/*if (menuIds.length == 0) {
		toastr.warning('', '请选择菜单');
		$(targetx).button('reset');
		return;
	}*/

	$.ajax({
		type : 'POST',
		dataType : "json",
		cache:false,
		url : ctx + 'sys/oper/roleAuth/ajaxSaveRoleAuth.do',
		data : {
			'roleId' : roleId,
			'menuIds' : menuIds,
			'belongSystem' : $('#belongSystem').val()
		},
		success : function(data) {
			if ('success' == data) {
				ajaxRefreshMenuList();
				toastr.success('', '操作成功');
			}
			$(targetx).button('reset');
		},
		error : function(e) {
			toastr.warning('', '保存出错，请检查重新操作');
			$(targetx).button('reset');
		}
	});

}

//所属系统
function changeBelogSystem(){
	$('#belongSystem').change('on',function(){
		ajaxRefreshMenuList();
	});
}